home *** CD-ROM | disk | FTP | other *** search
- Path: castle.nando.net!news
- From: actuary@nando.net (Bill McCarthy)
- Newsgroups: comp.lang.c
- Subject: Re: Can a function return a (pointer to a) function?
- Date: 27 Jan 1996 02:56:12 GMT
- Organization: News & Observer Public Access
- Message-ID: <4ec48c$kij@castle.nando.net>
- References: <4ebaaa$jh6@barnacle.iol.ie>
- Reply-To: actuary@nando.net (Bill McCarthy)
- NNTP-Posting-Host: vyger513.nando.net
- X-Newsreader: IBM NewsReader/2 v1.2
-
- In <4ebaaa$jh6@barnacle.iol.ie>,
- "John D. Hourihane" <hourihaj@iol.ie> writes:
-
- >I am trying to write a function which will return a pointer to a function,
- >but I'm having no luck.
- >
- >The toy program below illustrates (I hope) what I want to be able to do,
- >but as it stands it won't compile for me. The idea is that the call to
- >'(pick(ADD))' will return a pointer to the 'add' function which is then
- >dereferenced and used.
- >
- >But like I say, it doesn't compile. It complains 'Declaration terminated
- >incorrectly' as I declare 'pick'. I'm using Turbo C/C++.
- >
- >Any reply, posted here or by email, would be great.
- >
- >/* The toy program, to use a function that returns a
- > * pointer to a function.
- > */
- >
- >#include <stdio.h>
- >
- >#define ADD 0
- >#define MULTIPLY 1
- >
- >int add(int x, int y);
- >int multiply(int x, int y);
- >
- >/* pick returns a pointer to a function which will operate on two integers */
- >(int f(int, int)) *pick(int s);
-
- Replace above with:
-
- int (*pick(int))(int, int);
-
- >
- >int main()
- >{
- > printf("5 + 4 = %d\n", (*(pick(ADD)))(5,4));
- > printf("5 * 4 = %d\n", (*(pick(MULTIPLY)))(5,4));
- > return 0;
- >}
- >
- >int add(int x, int y)
- >{ return x + y; }
- >
- >int multiply(int x, int y)
- >{ return x * y; }
- >
- >(int f(int, int)) *pick(int s)
-
- And replace the above line with:
-
- int (*pick(int s))(int, int)
-
- >{ if (s == ADD)
- > return add;
- > return multiply;
- >}
-
- Bill McCarthy
- actuary@nando.net
- Wendell, NC USA
-
-